const fs = require("fs");
const stat = require("util").promisify(fs.stat);
const readDir = require("util").promisify(fs.readdir);
const path = require("path");
const handlebars = require("handlebars");
console.log("handlebars: " + handlebars.toString());
const config = require("../config/defaultConfig");

const tplPath = path.join(__dirname, "../template/dir.tpl");
const source = fs.readFileSync(tplPath, "utf-8");
console.log("source: " + source);
const template = handlebars.compile(source);
console.log("template: %j", template);

module.exports = async function (req, res, filePath) {
    try {
        const stats = await stat(filePath);

        //如果是文件
        if (stats.isFile()) {
            res.statusCode = 200;
            res.setHeader("Content-Type", "text/plain; charset=utf8");


            fs.createReadStream(filePath).pipe(res);
            /**
             * 上面的流处理代码等于下面的操作。但是操作会有效率问题
             */
            // fs.readFile(filePath, (error, data) => {
            //     res.end(data);
            // });


            //如果是文件夹
        } else if (stats.isDirectory()) {
            const files = await readDir(filePath);
            res.statusCode = 200;
            res.setHeader("Content-Type", "text/html");

            //由于files是一个数组，使用join方法添加间隔符号，打印出来数组的名字
            // res.end(files.join(", "));

            const dir = path.relative(config.root, filePath);
            const data = {
                files: files,
                title: path.basename(filePath),
                dir: dir ? `/${dir}` : "",
            };
            var result = template(data);
            console.log(result);
            res.end(result);
        }

    } catch (exception) {
        console.err(exception);
        res.statusCode = 404;
        res.setHeader("Content-Type", "text/plain");
        res.end(`${filePath} is not found or ${exception}`);
    }
};
